//
//  ALPS_ListenViewController.m
//  Alps
//
//  Created by dllo on 16/6/8.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "ALPS_ListenViewController.h"
#import "ALPS_ListenModel.h"
#import "ALPS_ListenTableViewCell.h"
#import "ALPS_SpecialIntroViewController.h"

@interface ALPS_ListenViewController ()<UITableViewDelegate, UITableViewDataSource>
/** 主界面 */
@property (nonatomic, strong) UITableView *tableView;
/** 数据源数组 */
@property (nonatomic, strong) NSMutableArray *dataSource;
/** 网络请求中页码 */
@property (nonatomic, assign) NSInteger pageNumber;
/** 存放数据字典 */
@property (nonatomic, strong) NSMutableDictionary *timeDic;
/** 时间戳转换出的时间 */
@property (nonatomic, strong) NSString *currentDateStr;
/** 存放时间戳数组 */
@property (nonatomic, strong) NSMutableArray *titleArray;
@end

@implementation ALPS_ListenViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setLeftBackButton];
    [self setMainTableView];
    [self getDataByPageNum:1 CategoryId:self.categoryId];
}

- (void)setMainTableView
{
    self.dataSource = [NSMutableArray array];
    self.titleArray = [NSMutableArray array];
    self.timeDic = [NSMutableDictionary dictionary];
    self.pageNumber = 1;
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"精品听单";
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreeWidth, ScreeHeight - 64) style:UITableViewStylePlain];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_tableView];
    
    [self.tableView registerClass:[ALPS_ListenTableViewCell class] forCellReuseIdentifier:@"cell"];
    
    
    //下拉刷新:
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self reloadData];
    }];
    
    [header setTitle:@"下拉可以刷新..." forState:MJRefreshStateIdle];
    [header setTitle:@"松开即可刷新" forState:MJRefreshStatePulling];
    [header setTitle:@"玩命加载中..." forState:MJRefreshStateRefreshing];
    
    self.tableView.mj_header = header;
    //上拉加载:
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self getMoreData];
    }];
}

#pragma mark -- 解析数据
- (void)getDataByPageNum:(NSInteger)number
              CategoryId:(NSInteger)categoryId
{
    if (self.whichPage == 1) {
        [WSSNetTool GetNetByURL:[NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/discovery/v2/category/subjects?categoryId=%ld&device=iPhone&page=%ld&per_page=20&scale=3", categoryId, number] body:nil headers:nil response:WSSJSON success:^(id result) {
            NSArray *arr = [result objectForKey:@"list"];
            for (NSDictionary *dic in arr) {
                ALPS_ListenModel *model = [[ALPS_ListenModel alloc] initWithDic:dic];
                [self.dataSource addObject:model];
                //转换时间戳
                NSString *str = [NSString stringWithFormat:@"%ld", model.releasedAt];
                NSTimeInterval time = [str doubleValue] / 1000;
                NSDate *detailDate = [NSDate dateWithTimeIntervalSince1970:time];
                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                [dateFormatter setDateFormat:@"MM/yyyy"];
                self.currentDateStr = [dateFormatter stringFromDate:detailDate];
                
                if ([self.timeDic.allKeys containsObject:self.currentDateStr]) {
                    [[self.timeDic objectForKey:self.currentDateStr] addObject:model];
                } else {
                    NSMutableArray *array = [NSMutableArray array];
                    [array addObject:model];
                    [self.titleArray addObject:self.currentDateStr];
                    [self.timeDic setObject:array forKey:self.currentDateStr];
                }
            }
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
            if (self.pageNumber == [[result objectForKey:@"maxPageId"] integerValue]) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
            [self.tableView reloadData];
        } failure:^(NSError *error) {
            
        }];
    } else {
    [WSSNetTool GetNetByURL:[NSString stringWithFormat:@"http://mobile.ximalaya.com/m/subject_list?device=iPhone&page=%ld&per_page=20&scale=2&statEvent=pageview%%2Fsubjectlist%%40精品听单&statModule=精品听单_更多&statPage=tab%%40发现_推荐", number] body:nil headers:nil response:WSSJSON success:^(id result) {
        NSArray *arr = [result objectForKey:@"list"];
        for (NSDictionary *dic in arr) {
            ALPS_ListenModel *model = [[ALPS_ListenModel alloc] initWithDic:dic];
            [self.dataSource addObject:model];
            //转换时间戳
            NSString *str = [NSString stringWithFormat:@"%ld", model.releasedAt];
            NSTimeInterval time = [str doubleValue] / 1000;
            NSDate *detailDate = [NSDate dateWithTimeIntervalSince1970:time];
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"MM/yyyy"];
            self.currentDateStr = [dateFormatter stringFromDate:detailDate];
            
            if ([self.timeDic.allKeys containsObject:self.currentDateStr]) {
                [[self.timeDic objectForKey:self.currentDateStr] addObject:model];
            } else {
                NSMutableArray *array = [NSMutableArray array];
                [array addObject:model];
                [self.titleArray addObject:self.currentDateStr];
                [self.timeDic setObject:array forKey:self.currentDateStr];
            }
        }
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        if (self.pageNumber == [[result objectForKey:@"maxPageId"] integerValue]) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        
    }];
    }
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.timeDic.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger number = [[self.timeDic valueForKey:[self.titleArray objectAtIndex:section]] count];
    return number;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return ScreeHeight / 6.67;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ALPS_ListenTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.selectionStyle = 0;
    ALPS_ListenModel *model = [[self.timeDic objectForKey:[self.titleArray objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
    cell.model = model;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ALPS_ListenModel *model = [[self.timeDic objectForKey:[self.titleArray objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
    ALPS_SpecialIntroViewController *SIVC = [[ALPS_SpecialIntroViewController alloc] init];
    SIVC.specialId = model.specialId;
    [self.navigationController pushViewController:SIVC animated:YES];
}

- (void)reloadData
{
    [self.dataSource removeAllObjects];
    [self.titleArray removeAllObjects];
    [self.timeDic removeAllObjects];
    [self getDataByPageNum:1 CategoryId:self.categoryId];
    [self.tableView reloadData];
    self.pageNumber = 1;
}

- (void)getMoreData
{
    self.pageNumber++;
    [self getDataByPageNum:self.pageNumber CategoryId:self.categoryId];
}

#pragma mark -- tableView的section取消浮动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat sectionHeaderHeight = 40;
    if (scrollView.contentOffset.y <= sectionHeaderHeight&&scrollView.contentOffset.y >= 0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    }
    else if (scrollView.contentOffset.y >= sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreeWidth, 40)];
    
    UIImageView *leftArrow = [[UIImageView alloc] initWithFrame:CGRectMake(0, 10, 30, 30)];
    leftArrow.image = [UIImage imageNamed:@"toolbar_play_n"];
    [headerView addSubview:leftArrow];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(28, 10, ScreeWidth, 30)];
    label.text = [self.titleArray objectAtIndex:section];
    label.font = [UIFont systemFontOfSize:17];
    
    [headerView addSubview:label];
    
    return headerView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreeWidth, 10)];
    footerView.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1];
    return footerView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
